package edu.friday.common.security.service;

import edu.friday.common.enums.UserStatus;
import edu.friday.common.security.LoginUser;
import edu.friday.model.SysUser;
import edu.friday.model.vo.SysUserVO;
import edu.friday.service.SysUserService;
import edu.friday.utils.BeanUtils;
import edu.friday.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysPermissionService sysPermissionService;
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //数据有效性验证
        //用户数据验证
       SysUser sysUser= sysUserService.selectUserByUserName(userName);
       if(StringUtils.isNull(sysUser)){
           System.out.println("登录用户不存在！");
       }else if(UserStatus.DELETED.getCode().equals(sysUser.getDelFlag())){
           System.out.println("登录用户已删除");
       }else if(UserStatus.DISABLE.getCode().equals(sysUser.getStatus())){
           System.out.println("登录用户已停用");
       }
        //封装并返回UserDetails
        return createLoginUser(sysUser);
    }

    private UserDetails createLoginUser(SysUser sysUser) {
        SysUserVO sysUserVO =new SysUserVO();
        BeanUtils.copyProperties(sysUser,sysUserVO);
        return new LoginUser(sysUserVO,sysPermissionService.getMenuPermission(sysUserVO));
    }
}
